<template>
	<view class="dynamic-form">
		<!--  可配置区域 -->
		<view class="dynamic-form-data">
			<view v-for="(field, index) in feildData" :key="index" class="dynamic-form-item"
			v-if="field.isShow === null || field.isShow === undefined || field.isShow"
			>
				<view v-if="field.isShow === null || field.isShow === undefined || field.isShow"
					class="dynamic-form-item__row">
					<view class="dynamic-form-item__label">
						<uni-text>{{ field.label }}</uni-text>
						<uni-text v-if="field.required" class="required">*</uni-text>
					</view>
					<view class="dynamic-form-item__desc">
						<DynamicField :fieldKey="field.key" :formData="formData" :field="field" :isEdit="isEdit"
							@update-form-data="updateFormData" />
					</view>
				</view>
				<view v-if="errors[field.key]" class="dynamic-form-item__error">
					<text class="error">{{ errors[field.key] }}</text>
				</view>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="flex flex-wrap diygw-col-24 flex-direction-column diygw-bottom">
			<view class="flex diygw-col-24">
				<button style="color: #fbf7f7 !important" @click="onCancel()"
					class="diygw-btn gradual-blue radius-xl flex-sub margin-xs button-button-clz">取消</button>
				<button @click="onSave" class="diygw-btn cyan radius-xl flex-sub margin-xs button-button-clz">
					{{ save ? '保存' : '商品入库' }}
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex';
	import DynamicField from '@/components/fields/DynamicField.vue';
	import dataDictionary from '@/common/data/dataDictionary.js';
	import feildData from '@/common/data/goodsStoreIn/feildData.js';

	import {
		formatTime
	} from '@/common/util.js'

	export default {
		components: {
			DynamicField,
		},
		data() {
			return {
				isEdit: true, // 是否为编辑模式，false 为查看模式
				updateFlag: false,
				dataDictionary: dataDictionary.goods, //数据字典
				formData: {},
				goodsData: {},
				errors: {
					name: "",
					stock: "",
				},
				feildData: feildData,
				save: false,
				storeOpt: [],
				optCodes: ["platInfo", "goodSource", "goodPurpose"],
				opts: []
			};
		},

		computed: {
			...mapGetters({
				userInfo: 'user/info',
				hasLogin: 'user/hasLogin'
			}),
		},

		onLoad(option) {
			if (option.goodsData) {
				this.goodsData = JSON.parse(option.goodsData);
				this.formData.goodsId = this.goodsData.id;
			}
			this.formData.storeId = this.userInfo.storeId;
			this.formData.storeName = this.userInfo.storeName;
			this.initFeildOpts();
		},

		methods: {

			/**
			 * 查询枚举值信息
			 */
			initFeildOpts() {
				let apiParam = "";
				this.optCodes.forEach((item, index) => {
					if (!apiParam) {
						apiParam = "classCodes=" + item;
					} else {
						apiParam = apiParam + "&classCodes=" + item;
					}
				});

				this.$api.dataOptsByCodes(apiParam).then(result => {
					if (result && result.code == "200") {
						this.opts = result.data;
					}
					this.updateFieldOpts();
				}).catch(res => {
					// 失败进行的操作
					uni.showToast({
						title: "查询失败!",
						duration: 3000
					});
					return;
				});
			},


			updateFieldOpts() {
				// 获取用户权限
				if (this.userInfo.storeId && this.userInfo.storeName) {
					this.storeOpt.push({
						value: parseInt(this.userInfo.storeId),
						text: this.userInfo.storeName,
					});
					// let storeIds = [];
					// Object.entries(this.userInfo.authInfos).forEach(([key, value]) => {
					// 	for (let i = 0; i < value.length; i++) {
					// 		if (storeIds.includes(value[i].storeId)) {
					// 			continue;
					// 		} else {
					// 			this.storeOpt.push({
					// 				value: value[i].storeId,
					// 				text: value[i].storeName,
					// 			});
					// 			storeIds.push(value[i].storeId);
					// 		}
					// 	}
					// });
				}

				if (this.feildData) {
					let roleCodes = this.userInfo?.roleCodes  ? this.userInfo?.roleCodes : [];
					for (let i = 0; i < this.feildData.length; i++) {
						let obj = this.feildData[i];
						
						if(obj.auth && roleCodes.includes[obj.auth]){
							// 字段根据权限控制
							obj.isShow = true;
						}
						
						if (this.opts && this.opts[obj.optKey]) {
							obj.options = this.opts[obj.optKey];
						}else if (this.goodsData && obj.key === 'goodsId') {
							obj.options = [{
								value: this.goodsData.id,
								text: this.goodsData.name,
							}];
						}
						
						
					}
				}
			},

			updateFormData(key, newFormData) {
				if (this.formData[key] == newFormData[key]) {
					return;
				}
				console.log("修改前的值======" + key + ":", this.formData[key])
				this.formData = newFormData; // 更新父组件的值
				console.log("修改后的值======" + key + ":", this.formData[key])

				if (!this.feildData) {
					return;
				}
				for (let i = 0; i < this.feildData.length; i++) {
					let obj = this.feildData[i];
					if (!obj.relations || !obj.relations[key]) {
						continue;
					}
					if (!obj.relations[key].includes(this.formData[key])) {
						obj.isShow = false;
					} else {
						obj.isShow = true;
					}
				}
			},


			showRelationFeild(keys, isShow) {
				if (this.feildData) {
					for (let i = 0; i < this.feildData.length; i++) {
						let obj = this.feildData[i];
						if (obj.key == 'onlinePlat' || obj.key == 'platGoodId') {
							obj.isShow = isShow;
						}
					}
				}
			},

			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.formData.image = res.tempFilePaths[0];
					},
				});
			},

			// 商品名称验证
			validateName() {
				if (!this.formData.name) {
					this.errors.name = "商品名称不能为空";
				} else if (/[^a-zA-Z0-9\u4e00-\u9fa5]/.test(this.formData.name)) {
					this.errors.name = "商品名称不能包含非法字符";
				} else {
					this.errors.name = "";
				}
			},

			// 商品入库数量验证
			validateStock() {
				if (!this.formData.stock) {
					this.errors.stock = "商品入库数量不能为空";
				} else if (this.formData.stock < 0) {
					this.errors.stock = "商品入库数量不能小于0";
				} else {
					this.errors.stock = "";
				}
			},

			// 选择商品分类
			onCategoryChange(e) {
				this.formData.category = this.categoryOptions[e.detail.value];
			},

			// 选择商品来源
			onSourceChange(e) {
				this.formData.source = this.sourceOptions[e.detail.value];
			},

			// 选择商品购买时间
			onBuyAtChange(e) {
				this.formData.buyAt = e.detail.value;
			},

			// 选择商品状态
			onStatusChange(e) {
				this.formData.status = e.detail.value; // 更新商品状态
				if (this.formData.status === 0) {
					this.formData.arrivalAt = ""; // 如果状态为“未到货”，清空到货时间
				}
			},

			// 选择商品到货时间
			onArrivalAtChange(e) {
				this.formData.arrivalAt = e.detail.value;
			},

			// 保存
			async onSave() {
				if (this.errors.name || this.errors.stock) {
					uni.showToast({
						title: "请检查表单内容",
						icon: "none",
					});
					return;
				}
				this.$api.goodsInSave(this.formData).then(result => {
					if (!this.formData.id && result && Number.isInteger(result)) {
						this.formData.id = result;
						this.save = true;
						this.handleSubmit()
					} else if (this.formData.id && result && Number.isInteger(result)) {
						// 成功处理
						uni.showToast({
							title: "保存成功",
							duration: 1500
						});
					} else {
						uni.showToast({
							title: "保存失败",
							duration: 1500
						});
					}
				}).catch(res => {
					// 失败进行的操作
					uni.showToast({
						title: "保存失败!",
						duration: 1500
					});
					return;
				})
			},

			// 使用示例
			async handleSubmit() {
				await this.showToastAndThen({
					title: '入库成功',
					icon: 'success',
					duration: 1500
				});
				// Toast关闭后执行的逻辑
				this.onCancel();
			},

			// 封装工具函数
			showToastAndThen(options) {
				return new Promise((resolve) => {
					uni.showToast({
						title: options.title,
						icon: options.icon || 'none',
						duration: options.duration || 1500,
						mask: options.mask || false
					});

					setTimeout(() => {
						resolve();
					}, options.duration || 1500);
				});
			},

			// 取消
			onCancel() {
				uni.navigateBack();
			},

			selectConfig(selectInfo) {
				this.formData.goodsId = selectInfo.id;
				this.formData.goodsName = selectInfo.name;
				this.goodsData = selectInfo;
				this.updateFieldOpts();
			},
		},
	};
</script>

<style lang="less" scoped>
	@import url("@/common/css/dynamic-form.less");
</style>
<style lang="scss" scoped>
	.popup-content {
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 15px;
		height: 200rpx;
		background-color: #fff;
	}

	.popup-content .text {
		font-size: 14px;
	}


	@mixin flex {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}

	@mixin height {
		/* #ifndef APP-NVUE */
		height: 100%;
		/* #endif */
		/* #ifdef APP-NVUE */
		flex: 1;
		/* #endif */
	}

	.box {
		@include flex;
	}

	.btns {
		@include flex;
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}

	.btn {
		margin: 6rpx !important;
		background-color: var(--cyan) !important;
		color: var(--white) !important;
		flex: 1;
		border-radius: 200px !important;
		padding: 0 20rpx;
		font-size: 14px;
		height: 64rpx !important;
		position: relative;
		border: 0px;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
		line-height: 1 !important;
		text-align: center;
		text-decoration: none;
		overflow: visible;
		transform: translate(0px, 0px);
	}


	.button {
		@include flex;
		align-items: center;
		justify-content: center;
		flex: 1;
		height: 35px;
		margin: 0 5px;
		border-radius: 5px;
	}

	.example-body {
		background-color: #fff;
		padding: 10px 0;
	}

	.button-text {
		color: #fff;
		font-size: 12px;
	}


	.popup-height {
		@include height;
		width: 200px;
	}

	.text {
		font-size: 12px;
		color: #333;
	}
</style>